import { DataSource } from 'typeorm';
import { User } from './src/users/users.entity';
import { AppModule } from './src/app.module';
import * as bcrypt from 'bcryptjs';

async function hashExistingPasswords() {
  // 创建数据源配置
  const dataSource = new DataSource({
    type: 'postgres',
    host: process.env.DATABASE_URL ? undefined : '43.162.111.101',
    port: process.env.DATABASE_URL ? undefined : 5432,
    username: process.env.DATABASE_URL ? undefined : 'myuser',
    password: process.env.DATABASE_URL ? undefined : '123456',
    database: process.env.DATABASE_URL ? undefined : 'dating_app',
    url: process.env.DATABASE_URL,
    entities: [User],
    synchronize: false,
  });

  try {
    // 初始化数据源
    await dataSource.initialize();
    console.log('DataSource initialized successfully');

    const userRepo = dataSource.getRepository(User);
    const users = await userRepo.find();

    const saltRounds = 10;
    let hashedCount = 0;

    for (const user of users) {
      // 防止重复哈希：判断是否已经是 bcrypt 格式
      if (!user.password.startsWith('$2b$')) {
        user.password = await bcrypt.hash(user.password, saltRounds);
        await userRepo.save(user);
        console.log(`Hashed password for user ${user.phone}`);
        hashedCount++;
      }
    }

    console.log(`All passwords have been hashed! Hashed ${hashedCount} passwords.`);
  } catch (error) {
    console.error('Error hashing passwords:', error);
  } finally {
    // 关闭数据源连接
    if (dataSource.isInitialized) {
      await dataSource.destroy();
      console.log('DataSource connection closed');
    }
    process.exit(0);
  }
}

// 执行密码哈希函数
hashExistingPasswords()
  .then(() => process.exit(0))
  .catch((err) => {
    console.error(err);
    process.exit(1);
  });